package cn.wolfcode.wolf2w.resolver;

import cn.wolfcode.wolf2w.annotation.UserParam;
import cn.wolfcode.wolf2w.cache.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.domain.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Parameter;

//public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {
//
//    @Autowired
//    private IUserInfoRedisService userInfoRedisService;
//
//    //那些参数需要处理
//    @Override
//    public boolean supportsParameter(MethodParameter parameter) {
//        return parameter.getParameterType() == UserInfo.class
//                && parameter.hasParameterAnnotation(UserParam.class);
//    }
//
//    //处理参数的方法
//    @Override
//    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
//                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
//        HttpServletRequest req =  webRequest.getNativeRequest(HttpServletRequest.class);
//        String token = req.getHeader("token");
//        UserInfo userInfo = userInfoRedisService.getUserByToken(token);
//        return userInfo;
//    }
//}
    public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver{
        @Autowired
        private IUserInfoRedisService userInfoRedisService;

        //哪些参数需要处理
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType()==UserInfo.class && methodParameter.hasParameterAnnotation(UserParam.class);
    }

        //处理参数的方法
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest req = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = req.getHeader("token");
        UserInfo userInfo = userInfoRedisService.getUserByToken(token);
        return userInfo;
    }
}






